<?php
namespace Home\Controller;

use Think\Controller;
use Common\Common;

class IndexController extends Controller
{
    /**
     * 验证用户信息
     * 1、验证session获取用户信息
     * 2、session不存在时授权通过openid在数据库中获取用户信息
     * 3、数据库不存在是通过openid和access_token拉取用户信息，并存入数据库
     */
    private function _check()
    {

       // todo:测试用途，上线请注释
 //        $openid="oskIr0fFMeb0j3ngbXNpuKdYeLoQ";
 //       $user=D('User')->where(array('openid'=>$openid))->find();//获取当前用户
 //       $_SESSION['lblUser'] = $user;
 //       return $user;

        $user = isset( $_SESSION['lblUser']) ?  $_SESSION['lblUser'] : false;
        if ($user) {
            $_SESSION['lblUser'] = $user;//将$user存入session
            return $user;
        }

        $wechat = D('BindWechat')->getBindWechat();
        $weixin = new Common\WeixinCommon();
        if (isset($_GET['code']) && $_GET['code'] != 'authdeny') {//授权后获取code
            $code = $_GET['code'];
            $arr = $weixin->getAccessTokenByCode($wechat['appid'], $wechat['appsecret'], $code);//获取openid，access_token，refresh_token
            if ($arr) {
                $openid = $arr['openid'];
                $access_token = $arr['access_token'];
                $u = $weixin->getUserInfo($access_token, $openid);//拉取用户基本信息
                $userInfo = array('openid' => $u['openid'], 'sex'=>$u['sex'],'nickname' => $u['nickname'], 'headimgurl' => $u['headimgurl']);
                $user = D('User')->where(array('openid'=>$openid))->find();//数据库获取用户信息
                if (count($user) <= 0) {//如果用户不存在则刷新access_token并拉取用户基本信息存入数据库
                    $id=D('User')->add($userInfo);//添加用户
                    $userInfo['id']=$id;
                } else {
                    $where['openid'] = $user['openid'];
                    D('User')->where($where)->save($userInfo);//更新用户基本信息
                    $user = D('User')->where(array('openid'=>$openid))->find();//数据库获取用户信息
                    $userInfo = $user;
                }
                $_SESSION['lblUser'] = $userInfo;//将$userInfo存入session
                return $userInfo;
            } else {
                return false;//授权失败
            }
        } else {
            $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];//获取完整的url地址
            $url = $weixin->oauth($url, $wechat['appid'], "snsapi_userinfo");//授权
            redirect($url);
        }
    }

    /*
     * 首页
     */
    public function index()
    {
        $user=$this->_check();

        if(!$user) return;
        $userInfo = D('User')->where(array('id'=>$_SESSION['lblUser']['id']))->find();
        if($userInfo['status']==1){
            redirect(U('UserCenter/center'));
        }
        $courses = M('courses')->select();
        $class = M('class')->select();
        $this->assign('courses',$courses);
        $this->assign('class',$class);
        $this->display('Index/home');
    }



    /**
     * 士兵报名
     */
    public function home(){
        $user=$this->_check();

        if(!$user) return;
        $userInfo = D('User')->where(array('id'=>$_SESSION['lblUser']['id']))->find();
        if($userInfo['status']==1){
            redirect(U('UserCenter/center'));
        }
        $courses = M('courses')->select();
        $class = M('class')->select();
        $this->assign('courses',$courses);
        $this->assign('class',$class);
        $this->display();
    }

    //用户报名
    public  function userUpdate(){
        $user=$this->_check();
        if(!$user) return;
        if($_POST){
            $data = I('post.');

            if($data['code'] != $_SESSION[$data['phone']."p"]['code']){
                $msg['error'] = '验证码错误';
                $this->ajaxReturn($msg);
            }
            if(empty($data['code'])){
                $msg['error'] = '验证码不能为空';
                $this->ajaxReturn($msg);
            }
            unset($data['code']);
            $data['gender'] = trim($data['gender']);
            $data['status'] = 1;
            if(D('User')->where(array('id'=>$user['id']))->save($data)){
                unset($_SESSION[$data['phone']."p"]);
                $msg['status'] =1;
                $msg['error'] = '报名成功';
                $this->ajaxReturn($msg);
            }else{
                $msg['error'] = '报名失败';
                $this->ajaxReturn($msg);
            }


        }
    }

    //课程下单
    public function order(){
        $user=$this->_check();

        if(!$user) return;
        if($_POST){
            $userInfo = D('User')->where(array('id'=>$_SESSION['lblUser']['id']))->find();
            if($userInfo['status'] == 0){
                $msg['error'] = '下单失败！你还没有报名，跳转报名界面。';
                $msg['status'] = 2;
                $this->ajaxReturn($msg);
            }
            $data['courses_id'] = I('post.courses_id');
            if(empty($data['courses_id'])){
                $msg['error'] = '下单失败！';
                $this->ajaxReturn($msg);
            }
            if(M('courses')->where(array('id'=>$data['courses_id'],'startime'=>array('lt',date('Y-m-d H:i:s',time()))))->find()){
                $msg['error'] = '当前期数已经开始或者已经结束，请选择其他期数！';
                $this->ajaxReturn($msg);
            }
            if(M('order')->where(array('courses_id'=>$data['courses_id'],'status'=>2,'user_id'=>$_SESSION['lblUser']['id']))->find()){
                $msg['error'] = '你已报名该期数，请选择其他期数！';
                $this->ajaxReturn($msg);
            }
            $data['create_time'] = time();
            $data['status'] = 1;
            $data['price'] = M('courses')->where(array('id'=>$data['courses_id']))->getField('money');
            $data['order_sn'] = time().rand(10000,99999);
            $data['user_id'] =$_SESSION['lblUser']['id'];
            if($msg['orderId'] = M('order')->add($data)){
                $msg['status'] =1;
                $msg['error'] = '下单成功';
                $msg['orderId'] = $msg['orderId'];
                $this->ajaxReturn($msg);
            }else{
                $msg['error'] = '下单失败';
                $this->ajaxReturn($msg);
            }
        }

    }

    public function wx_pay(){
        $user=$this->_check();

        if(!$user) return;
        $userInfo =  $_SESSION['lblUser'];
        $orderId = I('orderId');

        $dis = M('discount')->where(array('id'=>1))->getField('discount');
        if (!$dis){
            $dis = 10;
        }
        $info = M('order')->where(array('id'=>$orderId,'user_id'=>$userInfo['id']))->find();
        $wxpay = new Common\Wxpay();
        $courses_name = M('courses')->where(array('id'=>$info['courses_id']))->getField('name');
        $class_name= M('class')->where(array('id'=>$info['class_id']))->getField('name');
        $param['body'] = $courses_name.$class_name.$info['price'].'元';//主体描述
        $param['out_trade_no'] = $info['order_sn'];//订单号
        $param['total_fee'] = $info['price']*100*$dis/10;//支付金额，单位：分
        $param['openid'] = $userInfo['openid'];
        $param['notify_url'] = "http://wx.magicalthink.com/Home/Index/notify_url";

        $jsApiParameters = $wxpay->get_jsApiParameters($param);

        $this->assign('jsApiParameters', $jsApiParameters);
        $this->display();
    }

    /**
     * 微信支付通知地址
     */
    public function notify_url()
    {
        $postdata = file_get_contents('php://input');
        //将XML转为array
        if (!empty($postdata)) {
            //转换成json 写入文件
            $post_json = json_encode(simplexml_load_string($postdata, 'SimpleXMLElement', LIBXML_NOCDATA));
            $back = date('Y-m-d H:i:s', time()) . '——' . $post_json . "\r\n";
            file_put_contents('Public/txt/wx_back.txt', $back, FILE_APPEND);

            //把数据转换为数组
            $post_array = json_decode($post_json, true);
            //通过$post_array处理订单数据

            $order =M('order')->where(array('order_sn' => $post_array['out_trade_no']))->find();
            if (count($order) <= 0) {
                echo 'success';//订单不存在则直接提示微信支付成功，不需要再发起通知
                return;
            }
            if (!empty($order['transaction_id']) && !empty($order['time_end']) && $order['order_status'] != 1) {
                echo 'success';//订单状态已经改变，提示微信不需要再发起通知
                return;
            }

            //将微信返回的数据写入订单
            $up['transaction_id'] = $post_array['transaction_id'];
            $up['time_end'] = $post_array['time_end'];
            $up['status'] = 2;
            M('order')->where(array('id'=>$order['id']))->save($up);

            //写入消费记录

            echo "success";//提示微信支付成功
        }
    }

    /**
     * 获取验证码
     */

    public function code(){
        $user=$this->_check();

        if(!$user) return;
        $phone =  I('post.phone');
        if(!preg_match("/^1[34578]{1}\d{9}$/",$phone)){
            $msg = [
                'error' => 0,
                'msg' => '手机号码格式不正确'
            ];
            $this->ajaxReturn($msg);
        }


        $code = mt_rand(1000,9999);

        import('Org.Sms.top.TopClient');
        import('Org.Sms.top.ResultSet');
        import('Org.Sms.top.RequestCheckUtil');
        import('Org.Sms.top.TopLogger');
        import('Org.Sms.top.request.AlibabaAliqinFcSmsNumSendRequest');

        $c = new \TopClient;
        $c->appkey = '23666549';
        $c->secretKey = '093d7fa47b4e64b134296e1f086d1f00';
        $req = new \AlibabaAliqinFcSmsNumSendRequest;
        $req ->setExtend( "123456" );
        $req ->setSmsType( "normal" );
        $req ->setSmsFreeSignName( "铁牛工匠" );//来源于配置短信签名 下面列表中有签名名称
        $req ->setSmsParam( "{code:'{$code}'}" ); //变量来源于 配置短信模板 点击列表中的详情 模板内容的变量
        $req ->setRecNum( "$phone" ); //手机号
        $req ->setSmsTemplateCode("SMS_56585476"); //配置短信模板 列表中有模板id
        $resp = $c ->execute( $req );

        if($resp){
            $_SESSION[$phone."p"]['code'] = $code;
            $_SESSION[$phone."p"]['time'] = time();
            $msg = [
                'error' => 1,
                'msg' => '发送成功'
            ];
        }else{
            $msg = [
                'error' => 0,
                'msg' => '数据错误'
            ];
        }
        $this->ajaxReturn($msg);
    }

    public function  upload(){


        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =      './Uploads/'; // 设置附件上传根目录
        $upload->savePath  =      ''; // 设置附件上传（子）目录
// 上传文件

        $info   =   $upload->upload();

        if(!$info) {// 上传错误提示错误信息
            $data['error'] = '上传失败';
            $this->error($upload->getError());
        }else{// 上传成功 获取上传文件信息
            $data['status'] = 1;
            foreach($info as $file){
                $data['data'] = '/Uploads/'.$file['savepath'].$file['savename'];
            }
        }
        $this->ajaxReturn($data);
    }



}